package zhaoyong.wang.tlias.filetr;

import ch.qos.logback.core.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.coyote.Request;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.util.StringUtils;
import zhaoyong.wang.tlias.pojo.Result;
import zhaoyong.wang.tlias.utils.jwtUtils;

import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class Loginfilter  implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1、获取请求url
        String url = request.getRequestURL().toString();
        log.info("url:{}",url);
        //2、判断是否为登录请求，登录放行，其余进行token判断
        if (url.contains("/login")){
            log.info("登录操作，放行。。。");
            filterChain.doFilter(request,response);
            return;
        }
        //3、获取请求token
       String jwt = request.getHeader("token");
        log.info("当前jwt：{}",jwt);
        //4、判断token是否存在，不存在返回错误结果
        if (StringUtils.hasLength(jwt)){

            //5、解析token 判断是否正确 错误返回失败结果
            try {
                jwtUtils.parseJWT(jwt);
            } catch (Exception e) {
                log.info("解析令牌失败");
                Result error = Result.error("NOT_LOGIN");
                String notLogin = JSONObject.toJSONString(error);
                response.getWriter().write(notLogin);
                return;
            }
        }else {
            log.info("请求头为空，返回未登录信息");

            String NOTLOGIN = JSONObject.toJSONString(Result.error("NOT_LOGIN"));
            response.getWriter().write(NOTLOGIN);
            return;
        }


        //6、放行
        log.info("令牌合法");
        filterChain.doFilter(request,response);
    }
}
